package rexsee.dialog;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.browser.clazz.WindowCreateCloseListener;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;

public class RexseePopupWindow implements JavascriptInterface {

	public static final String INTERFACE_NAME = "PopupWindow";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseePopupWindow(childBrowser);
	}

	public static final String EVENT_ONPOPUPWINDOWDISMISSED = "onPopupWindowDismissed";

	private final Context mContext;
	private final Browser mBrowser;
	private final HashMap<String, PopupWindow> mMap;
	private boolean syncTag = false;

	public void destroyAll() {
		if (mMap.size() == 0) return;
		Collection<PopupWindow> collection = mMap.values();
		if (collection == null) return;
		Iterator<PopupWindow> iterator = collection.iterator();
		while (iterator.hasNext()) {
			PopupWindow w = iterator.next();
			if (w != null) w.destroy();
		}
	}

	public RexseePopupWindow(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
		mMap = new HashMap<String, PopupWindow>();
		mBrowser.eventList.add(EVENT_ONPOPUPWINDOWDISMISSED);
	}

	//JavaScript Interface 
	public void enableNewWindow(boolean enable) {
		if (enable) {
			mBrowser.setWindowCreateCloseListener(new WindowCreateCloseListener() {
				@Override
				public Browser getNewBrowser(Browser browser, boolean isDialog, boolean isUserGesture, boolean isLink) {
					String id = "NewWindow" + System.currentTimeMillis();
					show(id, null, "", "");
					return mMap.get(id).getBrowser();
				}
				@Override
				public void closeWindow(Browser browser) {
					if (browser.parentDialog != null) {
						mMap.remove(browser.parentDialog.getParentId());
						browser.parentDialog.doCancel();
					}
				}
			});
		} else {
			mBrowser.setWindowCreateCloseListener(null);
		}
	}
	public boolean isNewWindowEnabled() {
		return mBrowser.windowListener != null;
	}

	public void show(String url, String style) {
		show(null, url, style, "");
	}
	public void show(String url, String style, String clickCallback) {
		show(null, url, style, clickCallback);
	}
	public void show(String id, final String url, final String style, final String clickCallback) {
		final String dialogId = (id != null) ? id : url;
		if (mMap.containsKey(dialogId)) return;
		syncTag = false;
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					Runnable runnable = null;
					if (clickCallback != null && !clickCallback.trim().equals("")) {
						runnable = new Runnable() {
							@Override
							public void run() {
								mBrowser.function.load(clickCallback);
							}
						};
					}
					PopupWindow dialog = new PopupWindow(mBrowser, dialogId, url, style, runnable);
					mMap.put(dialogId, dialog);
					dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
						@Override
						public void onDismiss(DialogInterface dialog) {
							((PopupWindow) dialog).destroy();
							mMap.remove(dialogId);
							mBrowser.eventList.run(EVENT_ONPOPUPWINDOWDISMISSED, new String[]{dialogId});
						}
					});
					dialog.start();
				} catch (Exception e) {
					mBrowser.exception(getInterfaceName(), e);
				}
				syncTag = true;
			}
		});
		while (!syncTag) {
			try {
				Thread.sleep(100);
			} catch (Exception e) {

			}
		}
		return;
	}
	public void dismiss(String id) {
		if (!mMap.containsKey(id)) return;
		PopupWindow dialog = mMap.get(id);
		if (dialog != null) dialog.dismiss();
		mMap.remove(id);
	}
	public void dismissAll() {
		if (mMap.size() == 0) return;
		Set<String> keys = mMap.keySet();
		Iterator<String> iterator = keys.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			PopupWindow dialog = mMap.get(key);
			if (dialog != null) dialog.dismiss();
		}
		mMap.clear();
	}
	public void setStyle(String id, String style) {
		if (!mMap.containsKey(id)) return;
		mMap.get(id).setStyle(style);
	}
	public String getStyle(String id, String name) {
		return (!mMap.containsKey(id)) ? "" : mMap.get(id).getStyle(name);
	}
	public boolean exists(String id) {
		return mMap.containsKey(id);
	}
	public int size() {
		return mMap.size();
	}
	public String getIds() {
		String rtn = "";
		Set<String> ids = mMap.keySet();
		Iterator<String> iterator = ids.iterator();
		while (iterator.hasNext()) {
			if (!rtn.equals("")) rtn += ",";
			rtn += "\"" + iterator.next() + "\"";
		}
		return "[" + rtn + "]";
	}

	public void load(String id, String url) {
		if (!mMap.containsKey(id)) return;
		PopupWindow dialog = mMap.get(id);
		if (dialog != null) dialog.getBrowser().function.load(url);
	}
	public void loadHTML(String id, String html) {
		if (!mMap.containsKey(id)) return;
		PopupWindow dialog = mMap.get(id);
		if (dialog != null) dialog.getBrowser().function.loadHTMLWithoutHistory(html);
	}

}
